<?php
namespace app\index\controller;

use app\common\controller\IndexBase;
use think\Db;
use think\Validate;

use Overtrue\Socialite\SocialiteManager;
/**
 * 前台操作处理
 * @package app\index\controller
 */
class Action extends IndexBase
{
    # 登陆
    public function login()
    {
        $config = [
            'qq' => [
                'client_id'     => config('web.qq_app_id'),
                'client_secret' => config('web.qq_app_key'),
                'redirect'      => 'http://'.request()->host().'/callback',
            ],
        ];
        $socialite = new SocialiteManager($config);
        $response = $socialite->driver('qq')->redirect();
        $response->send();
    }
    # 登陆回调
    public function callback()
    {
        $config = [
            'qq' => [
                'client_id'     => config('web.qq_app_id'),
                'client_secret' => config('web.qq_app_key'),
                'redirect'      => 'http://'.request()->host().'/callback',
            ],
        ];
        $socialite = new SocialiteManager($config);
        $user = $socialite->driver('qq')->user();
        $data=[
            'uid'               =>$user['id'],
            'type'              =>$user['provider'],
            'nickname'          =>$user['nickname'],
            'avatar'            =>$user['avatar'],
            'last_login_time'   =>time(),
            'last_login_ip'     =>request()->ip()
        ];
        if (!$user_data=model('User')->getDataByWhere(['uid'=>$user['id']], '', '', true)) {
            $id=model('User')->addData($data);
        } else {
            if ($user_data['status']==0) {
                $this->error('对不起，由于您之前操作行为，您被后台限制登陆', 'index/index/index');
            }
            $id=model('User')->editData(['uid'=>$user['id']], $data);
        }
        $login_info=[
            'id'        =>  $id,
            'avatar'    =>  $data['avatar'],
            'nickname'  =>  $data['nickname'],
        ];
        session('user', $login_info);
        $this->success('登陆成功，欢迎来自'.$data['type'].'的用户', 'index/index/index');
    }
    # 登出
    public function logout()
    {
        session('user', null);
        $this->success('退出成功', 'index/index/index');
    }
    # 评论
    public function comment()
    {
        if (!request()->isAjax()) {
            $this->redirect('index/index/index');
        }
        $data=input('post.');
        $rule = [
            ['uid','require','用户参数缺少'],
            ['aid','require','文章参数缺少'],
            ['parent_id','require','评论参数缺少'],
            ['content','require','内容必需'],
            ['email','email','邮箱格式有误'],
        ];
        $validate = new Validate($rule);
        if (!$validate->check($data)) {
            return json(['errno'=>1,'msg'=>$validate->getError()]);
        }
        if (!empty($data['email'])) {
            model('User')->where(['id'=>session('user.id')])->setField('email', $data['email']);
        }
        if (!$result=model('Comment')->addData($data)) {
            return json(['errno'=>1,'msg'=>'对不起，由于某些原因评论失败']);
        }
        return json(['errno'=>0,'msg'=>'评论成功，请等待后台审核']);
    }
    # 邮件投稿
    public function sendEmail()
    {
        if (!request()->isAjax()) {
            $this->redirect('index/index/index');
        }
        $data=input('post.');
        $rule = [
            ['subject','require','主题必需'],
            ['content','require','内容必需'],
            ['captcha','require','验证码必需']
        ];
        $validate = new Validate($rule);
        if (!$validate->check($data)) {
            return json(['errno'=>1,'msg'=>$validate->getError()]);
        }
        if (!captcha_check($data['captcha'])) {
            return json(['errno'=>1,'msg'=>'验证码错误']);
        }
        $sendResult=sendMail(config('web.mail'), $data['subject'], $data['content']);
        if (1===$sendResult['errno']) {
            return json(['errno'=>1,'msg'=>$sendResult['msg']]);
        }
        return json(['errno'=>0,'msg'=>'邮件发送成功，站长将会尽快回复您']);
    }
    # 留言
    public function message()
    {
        if (!request()->isAjax()) {
            $this->redirect('index/index/index');
        }
        $data=input('post.');
        $rule = [
            ['uid','require','用户参数缺少'],
            ['email','email','邮箱格式有误'],
            ['content','require','内容必需']
        ];
        $validate = new Validate($rule);
        if (!$validate->check($data)) {
            return json(['errno'=>1,'msg'=>$validate->getError()]);
        }
        if (!empty($data['email'])) {
            model('User')->where(['id'=>session('user.id')])->setField('email', $data['email']);
        }
        if (!$result=model('Message')->addData($data)) {
            return json(['errno'=>1,'msg'=>'对不起，由于某些原因留言失败']);
        }
        return json(['errno'=>0,'msg'=>'留言成功，请等待后台审核']);
    }
}
